#通信
@messenger =
	#搜索数据
	searchData:{}
	#-----------------------公共
	#定时器
	_timer:0
	#时间间隔,单位秒
	_interval:40
	#关键词所在页
	_page:0
	#已经被点击的ID
	_clickedIds:[]
	#反馈在第几页找到
	postPage:(page)->
		unless chrome.proxy
			#如果没有代理api说明是浏览页面
			reqData = postPage:1
			reqData.findPage = page if page
			chrome.extension.sendRequest reqData
			return off
		page = page or @_page
		chrome.proxy.settings.get incognito:off, (config)->
			postData =
				sellername:$('#sellername').val()
				page:page
				t:Math.random()
			$.extend(postData,config.value.rules.proxyForHttp)
			$.getJSON "#{serverUrlPre}Visit/setPage",postData,showPercent
	#得到宝贝的id
	getItemId:(url)->
		regex = /[?&]id=(\d+)/ig
		r = regex.exec url
		if r
			return r[1]
		0


	#生命周期开始，开始发出心跳
	#@param integer t 单位为秒，表示心跳存活时间
	start: (t=40)->
		startT = new Date().getTime()
		@_timer = setInterval ->
			if new Date().getTime() - startT < t*1000 #这里的ms
				chrome.extension.sendRequest heart:1
		,1000
	#生命周期结束，不再发出心跳,可设置下一个生命周期在多少秒内必须开始，不然自动重新开始
	stop: (interval)->
		chrome.extension.sendRequest interval:interval if interval
		clearInterval @_timer
	#找到页码
	findPage:(page)->
		chrome.extension.sendRequest findPage:page
	#发送结果
	sendPage: ->
		chrome.extension.sendRequest postPage:1
	#下次
	next:->
		chrome.extension.sendRequest next:1
	#登录点击了一个宝贝
	clickItem:(url)->
		url = url or location.href
		id = @getItemId url
		if id
			chrome.extension.sendRequest clickItem:id
	#-----------------以下部分是背景页使用------------------------------

	#设置搜索数据
	setSearchData:(data)->
		@searchData = data
	#在某段时间，检测不到心跳。自动重新开始。
	_check:(interval)->
		interval = interval or @._interval
		if @_timer
			clearInterval @_timer
		that = this
		@_timer = setTimeout ->
			that.postPage -2
			gotaobao()
		,interval*1000
	#结束
	finish:->
		clearInterval @_timer
	#初始化
	_inited:0
	init:(interval)->
		@_clickedIds = []
		@_check(interval)
		if @_inited
			return 0
		@_inited = 1
		that = this

		chrome.extension.onRequest.addListener (request, sender, sendResponse)->
			ret = {}
			formData = $('form').serializeObject()
			unless request
				return off
			if request.findPage
				that._page = request.findPage
			if request.clickItem
				that._clickedIds.push request.clickItem
			if request.postPage
				that.postPage()
			if request.heart
				that._check()
				ret.alive = on
			if request.next
				setTimeout gotaobao,3000
			if request.interval
				that._interval = request.interval
			if request.searchData
				$.extend ret,that.searchData
			if request.clickedIds
				ret.clickedIds = that._clickedIds
			for k of request
				formKeyData = formData[k]
				if formKeyData
					ret[k] = formKeyData
			unless $.isEmptyObject(ret)
				sendResponse ret if sendResponse



